package cn.lizhangqu.kb.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 柯尊诚 on 2015/11/6.
 * kzc
 */
public abstract class CommonAdapter<T>  extends BaseAdapter{

    protected LayoutInflater inflater;
    protected Context context;
    private List<T> datas;
    private int layoutId;

    public CommonAdapter(Context context, int layoutId) {
        this.inflater = LayoutInflater.from(context);
        this.context = context;
        this.datas = new ArrayList<T>();
        this.layoutId = layoutId;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public T getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder vh = ViewHolder.getViewHolder(this.context, convertView, parent, this.layoutId, position);
        convert(vh, getItem(position));
        return vh.getConvertView();
    }

    public List<T> getDatas() {
        return datas;
    }

    public abstract void convert(ViewHolder vh, T item);

    public void addItem(List<T> items) {
        checkListNull();
        datas.addAll(items);
        notifyDataSetChanged();
    }

    public void clear() {
        if (datas == null && datas.isEmpty()) {
            return;
        }
        datas.clear();
        notifyDataSetChanged();
    }

    /**
     * 检查数据是否为空
     */
    public void checkListNull() {
        if (datas == null) {
            datas = new ArrayList<T>();
        }
    }


}
